package com.ex02.ylw;

import javax.servlet.ServletException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 一个简单的Http服务器，可以用来处理静态资源和Servlet
 *访问地址
 * http://127.0.0.1:8080/servlet/PrimitiveServlet?name=ylw
 * Created by yangliwei on 2017/7/21.
 */
public class HttpServer {
    ServerSocket server;
    private boolean shutdown = false;

    public void await() {
        try {
//            有个很奇怪的现象这个和tomcat的端口号居然不冲突
//            查看windows进程发现占用了的ip不一样 进程号也不一样，很奇怪吧
//            TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       4320
//            TCP    127.0.0.1:8080         0.0.0.0:0              LISTENING       1684
//            TCP    192.168.1.66:64429     101.227.143.109:8080   CLOSE_WAIT      7100
            server = new ServerSocket(8080, 5, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!shutdown) {
            try {
                Socket socket = server.accept();

                Request request = new Request();
                request.parse(socket.getInputStream());

                Response response = new Response(socket.getOutputStream());
                response.setRequest(request);

                if (request.getUri().startsWith("/servlet")) {
                    ServletProcess servletProcess = new ServletProcess();
                    servletProcess.process(request, response);
                } else {
                    StaticResourceProcess staticResourceProcess = new StaticResourceProcess();
                    staticResourceProcess.process(request, response);
                }
                socket.close();
                if (request.getUri().equals("finish")) {
                    shutdown = true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
    }
}
